package gff.model.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;


public class DAOUtil {
	
	private static final Logger log = Logger.getLogger( DAOUtil.class.getName() );
	
	private static Hashtable<String, DataSource> sources = new Hashtable<String, DataSource>();
	
    /**
     *  Cierra la conexion. <p>
     *  @param  cnx  conexion a cerrar.
     *  Implicitamente cierra los objetos relacionados.
     *
     */
    public static void closeConnection( Connection cnx ) {
        try {
        	if ( cnx != null ) {
        		cnx.close();
            }
        } catch ( SQLException e ) {
            log.error(e.getMessage());
        }
    }
    

    /**
     * Metodo para crear una conexion a la bd, mediante recursos jndi.
     * @param logicalDataSourceName
     * @return Connection conexion a la bd.
     * @throws NexindeDAOException Description of the Exception
     */
    public static Connection getConnection( String logicalDataSourceName ) throws Exception{
        Connection cnx = null;
        DataSource dataSource = null;

        try {
        	if (sources.get(logicalDataSourceName) == null) {
        		Context context = new InitialContext();
        	    dataSource = (DataSource) context.lookup(logicalDataSourceName);
        	    sources.put(logicalDataSourceName, dataSource);
        	   } else {
        		   dataSource = (DataSource) sources.get(logicalDataSourceName);
        	   }
        	   cnx = dataSource.getConnection();
        } catch ( NamingException e ) {
            String errorMsg = "Error en el data source ";
            log.error(e.getMessage());
            throw new Exception(errorMsg);
        } catch ( SQLException e ) {
            String errorMsg = "Error al obtener conexion (error en url, username o password)";
            log.error(e.getMessage());
            throw new Exception(errorMsg);
        } catch ( Exception e ) {
            String errorMsg = "Error al obtener conexion (error en url, username o password)";
            log.error(e.getMessage());
            throw new Exception(errorMsg);
        }
        return cnx;
    }
    
}
